package string;

import org.junit.Test;

import java.util.ArrayList;

public class ReverseWords {
    public static void main(String[] args) {
        ReverseWords re = new ReverseWords();
        String s = re.reverseWords("  the sky is blue");
        System.out.println(s);
    }
    public String reverseWords(String s) {
        ArrayList<String> result = new ArrayList<>();
        int begin = s.length() - 1;
        int current = s.length() - 1;
        while (current >= 0){
            if(s.charAt(current) == ' '){
                begin--;
                current--;
                continue;
            }
            while (current >= 0 && s.charAt(current) != ' '){
                current--;
            }
            String strRe = s.substring(current + 1, begin + 1);
            result.add(strRe);
            begin = current;
        }
        StringBuilder resultStr = new StringBuilder();
        for (int i = 0; i < result.size(); i++) {
            if(i < result.size() - 1){
                resultStr.append(result.get(i)+' ');
            }else {
                resultStr.append(result.get(i));
            }
        }
        return resultStr.toString();
    }
}
